package com.iyao_app.mvp.sign;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.model.LatLng;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.flipboard.bottomsheet.BottomSheetLayout;
import com.iyao_app.R;
import com.iyao_app.base.BaseActivityWithHead;
import com.iyao_app.entry.Manor;
import com.iyao_app.entry.MyInterestBean;
import com.iyao_app.entry.ResultModel;
import com.iyao_app.entry.SignCallBack;
import com.iyao_app.entry.UploadImage;
import com.iyao_app.entry.User;
import com.iyao_app.fragment.SignPersonFragment;
import com.iyao_app.fragment.SignPictureFragment;
import com.iyao_app.http.NetCallBack;
import com.iyao_app.http.NetUtils;
import com.iyao_app.http.RequestUrl;
import com.iyao_app.mvp.dialog.DialogSignActivity;
import com.iyao_app.mvp.search.SearchActivity;
import com.iyao_app.util.Contants;
import com.iyao_app.util.DbUtil;
import com.iyao_app.util.MessageEvent;
import com.iyao_app.util.PickImageLoader;
import com.iyao_app.util.ToastUtil;
import com.iyaowoqu.base_library.util.ImageUtils;
import com.iyaowoqu.base_library.util.KeyboardUtils;
import com.iyaowoqu.base_library.util.LogUtil;
import com.iyaowoqu.base_library.util.PopupWindowUtils;
import com.iyaowoqu.base_library.util.SPUtils;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageFolder;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.github.rockerhieu.emojicon.EmojiconEditText;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import top.zibin.luban.Luban;


/**
 * 作者 :  胡家兵
 * 时间 :  2017/11/22.
 */

public class SignActivity extends BaseActivityWithHead implements LoaderManager.LoaderCallbacks<Cursor> {
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.iv_title_xia_la)
    ImageView mIvTitleXiaLa;
    @BindView(R.id.iv_add_picture)
    ImageView mIvAddPicture;
    @BindView(R.id.iv_add_person)
    ImageView mIvAddPerson;

    @BindView(R.id.iv_more)
    ImageView mIvMore;
    @BindView(R.id.iv_picture)
    ImageView mIvPicture;
    @BindView(R.id.iv_delete)
    ImageView mIvDelete;
    @BindView(R.id.rl_picture)
    RelativeLayout mRlPicture;
    @BindView(R.id.bottomSheetLayout)
    BottomSheetLayout mBottomSheetLayout;
    @BindView(R.id.sdv_1)
    SimpleDraweeView mSdv1;
    @BindView(R.id.sdv_2)
    SimpleDraweeView mSdv2;
    @BindView(R.id.sdv_3)
    SimpleDraweeView mSdv3;
    @BindView(R.id.sdv_4)
    SimpleDraweeView mSdv4;
    @BindView(R.id.et_input)
    EmojiconEditText mEtInput;
    @BindView(R.id.tv_count)
    TextView tv_count;
    @BindView(R.id.rl_root_)
    RelativeLayout rl_root_;


    private SignPictureFragment signPictureFragment;
    private LoaderManager manager;
    private ImagePicker imagePicker;
    public final int IMAGE_PICKER = 1;
    public final int TAKE_PHOTO = 2;
    public final int SCREEN_CODE = 3;
    private final int REQUEST_CODE = 0;
    private final int REQUEST_CODE_STORAGE = 100;
    private String imagePath;
    private SignPersonFragment signPersonFragment;
    public List<MyInterestBean> dataList = new ArrayList<>();
    private List<MyInterestBean> selectList = new ArrayList<>();
    private LatLng myLatLng;
    private String city;
    private Manor manor;
    private String sceneId;
    private String typeCode;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign);
        ButterKnife.bind(this);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mBottomSheetLayout.setShouldDimContentView(false);
        mBottomSheetLayout.setPeekOnDismiss(false);
        mBottomSheetLayout.setUseHardwareLayerWhileAnimating(true);
        mBottomSheetLayout.setInterceptContentTouch(true);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
            if (checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                if (manager == null) {
                    manager = getSupportLoaderManager();
                    manager.initLoader(0, null, this);
                }
            }
        } else {
            if (manager == null) {
                manager = getSupportLoaderManager();
                manager.initLoader(0, null, this);
            }
        }
        initPicker();
        initData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void close(MessageEvent event) {
        if (event.getState() == MessageEvent.CLOSE) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initData() {
        manor = (Manor) getIntent().getSerializableExtra(Contants.THIRD_FIELD);
        myLatLng = new LatLng(manor.latitude, manor.longitude);
        city = getIntent().getStringExtra(Contants.OTHER_FIELD);
        if (manor != null) {
            typeCode = manor.typecode;
            sceneId = manor.sceneId;
            if (manor != null) {
                if (!TextUtils.isEmpty(manor.name)) {
                    mTvTitle.setText(manor.name);
                } else {
                    mTvTitle.setText(manor.address);
                }
            }
            getFriend();
        }
        mEtInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count == 0) {
                    tv_count.setVisibility(View.VISIBLE);
                } else {
                    tv_count.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        Observable.timer(1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.newThread())
                .subscribe(new Consumer<Long>() {

                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (SignActivity.this != null &&!SignActivity.this.isFinishing()) {
                            boolean homeFirst = SPUtils.getInstance().getBoolean(Contants.SIGN_FIRST, true);
                            if (homeFirst) {
                                fistEnter();
                            }
                        }

                    }
                });
    }

    @OnClick({R.id.iv_add_picture, R.id.iv_add_person, R.id.iv_more, R.id.iv_delete, R.id.tv_cancel, R.id.tv_sign, R.id.iv_title_xia_la,R.id.rl_root_})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_add_picture:
                KeyboardUtils.hideSoftInput(this);
                // Activity:
                AndPermission.with(this)
                        .requestCode(REQUEST_CODE_STORAGE)
                        .permission(Permission.STORAGE)
                        .rationale(new RationaleListener() {
                            @Override
                            public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                                // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                                AndPermission.rationaleDialog(SignActivity.this, rationale).show();
                            }
                        })
                        .callback(this)
                        .start();

                break;
            case R.id.iv_add_person:
                KeyboardUtils.hideSoftInput(this);
                if (dataList.size() == 0) {
                    Toast.makeText(this, "您目前还没有好友", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (signPersonFragment != null) {
                    LogUtil.e("===signPictureFragment==");
                    signPersonFragment.show(getSupportFragmentManager(), R.id.bottomSheetLayout);
                } else {
                    signPersonFragment = new SignPersonFragment();
                    signPersonFragment.show(getSupportFragmentManager(), R.id.bottomSheetLayout);
                    LogUtil.e("===signPictureFragment=null==");
                }
                break;
            case R.id.iv_more:
                KeyboardUtils.hideSoftInput(this);
                if (dataList.size() == 0) {
                    Toast.makeText(this, "您目前还没有好友", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (signPersonFragment != null) {
                    LogUtil.e("===signPictureFragment==");
                    signPersonFragment.show(getSupportFragmentManager(), R.id.bottomSheetLayout);
                } else {
                    signPersonFragment = new SignPersonFragment();
                    signPersonFragment.show(getSupportFragmentManager(), R.id.bottomSheetLayout);
                    LogUtil.e("===signPictureFragment=null==");
                }
                break;
            case R.id.iv_delete:
                KeyboardUtils.hideSoftInput(this);
                imagePath = null;
                mIvPicture.setImageDrawable(null);
                mRlPicture.setVisibility(View.GONE);
                break;
            case R.id.tv_cancel:
                KeyboardUtils.hideSoftInput(this);
                finish();
                break;

            case R.id.tv_sign:
                KeyboardUtils.hideSoftInput(this);
                showDialog();
                if (TextUtils.isEmpty(imagePath) || imagePath.startsWith("http")) {
                    complete();
                } else {
                    upLoadImage();
                }
                break;
            case R.id.iv_title_xia_la:
                KeyboardUtils.hideSoftInput(this);
                Intent intent = new Intent(SignActivity.this, SearchActivity.class);
                intent.putExtra(Contants.THIRD_FIELD, manor);
                intent.putExtra(Contants.OTHER_FIELD, city);
                intent.putExtra(Contants.CLASS_TYPE, 1);
                startActivityForResult(intent, REQUEST_CODE);
                break;
            case R.id.rl_root_:
                KeyboardUtils.hideSoftInput(this);
                break;
        }
    }

    @PermissionYes(REQUEST_CODE_STORAGE)
    private void getMultiYes(@NonNull List<String> grantedPermissions) {
        if (manager == null) {
            manager = getSupportLoaderManager();
            manager.initLoader(0, null, this);
        }
        if (signPictureFragment == null) {
            signPictureFragment = new SignPictureFragment();
        }
        if (allImages != null && allImages.size() == 0) {
            ImageItem e = new ImageItem();
            e.path = "1";
            allImages.add(e);
        }
        if (signPictureFragment != null)
            signPictureFragment.show(getSupportFragmentManager(), R.id.bottomSheetLayout);
    }

    @PermissionNo(REQUEST_CODE_STORAGE)
    private void getMultiNo(@NonNull List<String> deniedPermissions) {
        LogUtil.e("failure");
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            AndPermission.defaultSettingDialog(this, 100)
                    .setTitle("权限申请失败")
                    .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
                    .setPositiveButton("好，去设置")
                    .setNegativeButton("拒绝", null)
                    .show();

        }
    }

    public ArrayList<ImageItem> allImages = new ArrayList<>();   //所有图片的集合,不分文件夹
    private final String[] IMAGE_PROJECTION = {     //查询图片需要的数据列
            MediaStore.Images.Media.DISPLAY_NAME,   //图片的显示名称  aaa.jpg
            MediaStore.Images.Media.DATA,           //图片的真实路径  /storage/emulated/0/pp/downloader/wallpaper/aaa.jpg
            MediaStore.Images.Media.SIZE,           //图片的大小，long型  132492
            MediaStore.Images.Media.WIDTH,          //图片的宽度，int型  1920
            MediaStore.Images.Media.HEIGHT,         //图片的高度，int型  1080
            MediaStore.Images.Media.MIME_TYPE,      //图片的类型     image/jpeg
            MediaStore.Images.Media.DATE_ADDED};    //图片被添加的时间，long型  1450518608

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        CursorLoader cursorLoader = new CursorLoader(this, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION, null, null, IMAGE_PROJECTION[6] + " DESC");
        return cursorLoader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        if (data != null) {
            while (data.moveToNext()) {
                //查询数据
                String imageName = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[0]));
                String imagePath = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[1]));

                File file = new File(imagePath);
                if (!file.exists() || file.length() <= 0) {
                    continue;
                }

                long imageSize = data.getLong(data.getColumnIndexOrThrow(IMAGE_PROJECTION[2]));
                int imageWidth = data.getInt(data.getColumnIndexOrThrow(IMAGE_PROJECTION[3]));
                int imageHeight = data.getInt(data.getColumnIndexOrThrow(IMAGE_PROJECTION[4]));
                String imageMimeType = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[5]));
                long imageAddTime = data.getLong(data.getColumnIndexOrThrow(IMAGE_PROJECTION[6]));
                //封装实体
                ImageItem imageItem = new ImageItem();
                imageItem.name = imageName;
                imageItem.path = imagePath;
                imageItem.size = imageSize;
                imageItem.width = imageWidth;
                imageItem.height = imageHeight;
                imageItem.mimeType = imageMimeType;
                imageItem.addTime = imageAddTime;
                allImages.add(imageItem);

            }
            //防止没有图片报异常
            if (data.getCount() > 0 && allImages.size() > 0) {
                //构造所有图片的集合
                ImageFolder allImagesFolder = new ImageFolder();
                allImagesFolder.name = getResources().getString(com.lzy.imagepicker.R.string.ip_all_images);
                allImagesFolder.path = "/";
                allImagesFolder.cover = allImages.get(0);
                allImagesFolder.images = allImages;
            }
        }
        if (signPictureFragment != null)
            signPictureFragment.initData();
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.e("=-==onActivityResult !==" + resultCode);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                ImageItem imageItem = images.get(0);
                setImage(imageItem.path);
            }
        } else if (resultCode == RESULT_OK) {
            if (requestCode == ImagePicker.REQUEST_CODE_TAKE) {
                setImage(imagePicker.getTakeImageFile().getAbsolutePath());
            }
        } else if (requestCode == REQUEST_CODE && resultCode == SearchActivity.RESULT_CODE) {
            LogUtil.e("=-==REQUEST_CODE !==");
            if (data != null) {
                Manor manor = (Manor) data.getSerializableExtra(Contants.TYPE);
                myLatLng = new LatLng(manor.latitude, manor.longitude);
                String name = manor.name;
                sceneId = manor.sceneId;
                typeCode = manor.typecode;
                mTvTitle.setText(name);
                LogUtil.e(sceneId + "=-==REQUEST_CODE !==" + manor.toString());
            }
        }
    }

    public void setImage(final String imagePath) {
        signPictureFragment.dismiss();
        this.imagePath = imagePath;
        Glide.with(SignActivity.this).load(new File(imagePath)).asBitmap().into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                mRlPicture.setVisibility(View.VISIBLE);
                RelativeLayout.LayoutParams mRlPictureParams = (RelativeLayout.LayoutParams) mRlPicture.getLayoutParams();
                RelativeLayout.LayoutParams mIvPictureParams = (RelativeLayout.LayoutParams) mIvPicture.getLayoutParams();
                int width = resource.getWidth();
                int height = resource.getHeight();
                int maxWidth = (int) getResources().getDimension(R.dimen.x490);
                int realWidth = 0;
                int realHeight = 0;
                if (width >= maxWidth) {
                    realWidth = maxWidth;
                    if (height >= maxWidth) {
                        realHeight = maxWidth;
                    } else {
                        realHeight = height;
                    }
                } else {
                    realWidth = width;
                    realHeight = width;
                }
                mRlPictureParams.width = realWidth;
                mRlPictureParams.height = realHeight;
                mIvPictureParams.width = realWidth;
                mIvPictureParams.height = realHeight;
                if (resource != null && !resource.isRecycled()) {
                    resource.recycle();
                    resource = null;
                }
                Glide.with(SignActivity.this).load(new File(imagePath))
                        .override(realWidth, realHeight)
                        .into(mIvPicture);
                mIvPicture.setLayoutParams(mIvPictureParams);
                mRlPicture.setLayoutParams(mRlPictureParams);

            }
        }); //方法中设置asBitmap可以设置回调类型
    }

    private void initPicker() {
        imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PickImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(false);  //显示拍照按钮
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
        imagePicker.setMultiMode(false);
        imagePicker.setSaveRectangle(false); //是否按矩形区域保存
        imagePicker.setSelectLimit(1);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.CIRCLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素

    }

    private void check() {
        if (imagePicker == null) {
            initPicker();
        }
    }

    public void getPicture(int type) {
        KeyboardUtils.hideSoftInput(this);
        check();
        if (type == TAKE_PHOTO) {
            if (!(checkPermission(Manifest.permission.CAMERA))) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, ImageGridActivity.REQUEST_PERMISSION_CAMERA);
            } else {
                imagePicker.takePicture(this, ImagePicker.REQUEST_CODE_TAKE);
            }
        } else {
            Intent intent = new Intent(SignActivity.this, ImageGridActivity.class);
            startActivityForResult(intent, IMAGE_PICKER);
        }
    }

    public boolean checkPermission(@NonNull String permission) {
        return ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED;
    }

    public static final int REQUEST_PERMISSION_CAMERA = 0x02;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CAMERA) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                imagePicker.takePicture(this, ImagePicker.REQUEST_CODE_TAKE);
            } else {
                ToastUtil.showToast(this, "权限被禁止，无法打开相机");
            }
        }
    }

    public void addData(MyInterestBean demoData) {
        if (!selectList.contains(demoData)) {
            selectList.add(demoData);
            setData();
        }
    }

    public void deleteData(MyInterestBean demoData) {
        if (selectList.contains(demoData)) {
            selectList.remove(demoData);
            setData();
        }
    }

    private void setData() {
        LogUtil.e("==setData===");
        if (selectList.size() > 0) {
            mSdv1.setVisibility(View.VISIBLE);
            try {
                Uri uri = Uri.parse(selectList.get(0).getFavicon());
                ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                        .setResizeOptions(new ResizeOptions((int) getResources().getDimension(R.dimen.x80), (int) getResources().getDimension(R.dimen.x80)))
                        .build();
                PipelineDraweeController controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
                        .setOldController(mSdv1.getController())
                        .setImageRequest(request)
                        .build();
                mSdv1.setController(controller);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (selectList.size() > 1) {
                mSdv2.setVisibility(View.VISIBLE);
                try {
                    Uri uri = Uri.parse(selectList.get(1).getFavicon());
                    ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                            .setResizeOptions(new ResizeOptions((int) getResources().getDimension(R.dimen.x80), (int) getResources().getDimension(R.dimen.x80)))
                            .build();
                    PipelineDraweeController controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
                            .setOldController(mSdv2.getController())
                            .setImageRequest(request)
                            .build();
                    mSdv2.setController(controller);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                mIvMore.setVisibility(View.GONE);
                mSdv2.setVisibility(View.GONE);
            }
            if (selectList.size() > 2) {
                mSdv3.setVisibility(View.VISIBLE);
                try {
                    Uri uri = Uri.parse(selectList.get(2).getFavicon());
                    ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                            .setResizeOptions(new ResizeOptions((int) getResources().getDimension(R.dimen.x80), (int) getResources().getDimension(R.dimen.x80)))
                            .build();
                    PipelineDraweeController controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
                            .setOldController(mSdv3.getController())
                            .setImageRequest(request)
                            .build();
                    mSdv3.setController(controller);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                mIvMore.setVisibility(View.GONE);
                mSdv3.setVisibility(View.GONE);
            }
            if (selectList.size() > 3) {
                mSdv4.setVisibility(View.VISIBLE);
                mIvMore.setVisibility(View.VISIBLE);
                try {
                    Uri uri = Uri.parse(selectList.get(3).getFavicon());
                    ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                            .setResizeOptions(new ResizeOptions((int) getResources().getDimension(R.dimen.x80), (int) getResources().getDimension(R.dimen.x80)))
                            .build();
                    PipelineDraweeController controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
                            .setOldController(mSdv4.getController())
                            .setImageRequest(request)
                            .build();
                    mSdv4.setController(controller);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                mIvMore.setVisibility(View.GONE);
                mSdv4.setVisibility(View.GONE);
            }

        } else {
            mSdv1.setVisibility(View.GONE);
            mSdv2.setVisibility(View.GONE);
            mSdv3.setVisibility(View.GONE);
            mSdv4.setVisibility(View.GONE);
            mIvMore.setVisibility(View.GONE);
        }
    }

    private void getFriend() {
        User user = DbUtil.getUser();
        if (user == null) return;
        NetUtils.getInstance().getFriends(user.id, user.nickname, user.avatarUrl, user.sex, 1, 100, 3, new NetCallBack() {
            @Override
            public void onSuccess(String message, final int code, String response,
                                  final ResultModel model) {
                if (code == Contants.SUCCESS_CODE) {
                    if (model != null) {
                        List<MyInterestBean> modelList = (List<MyInterestBean>) model.getModelList();
                        if (modelList != null && modelList.size() > 0) {
                            dataList.addAll(modelList);
                        }
                    }
                }
            }

            @Override
            public void onFail(String message, int code) {

            }
        }, MyInterestBean.class);
    }

    private void upLoadImage() {
        Flowable.just(imagePath)
                .observeOn(Schedulers.io())
                .map(new Function<String, File>() {
                    @Override
                    public File apply(String s) throws Exception {
                        return Luban.with(SignActivity.this).load(s).get().get(0);
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<File>() {
                    @Override
                    public void accept(File file) throws Exception {
                        int[] imageInfo = ImageUtils.getImageWidthHeight(file);
                        LogUtil.e(imageInfo[0] + "=====" + imageInfo[1]);

                        final HashMap<String, Object> hashMap = new HashMap<>();
//                        File value = new File(imagePath);
                        hashMap.put("file", file);
                        NetUtils.getInstance().uploadImage(RequestUrl.UPLOAD_FILE, imageInfo[0], imageInfo[1], hashMap, new NetCallBack() {
                            @Override
                            public void onSuccess(final String message, final int code, String response, final ResultModel model) {
                                if (code == Contants.SUCCESS_CODE) {
                                    UploadImage uploadImage = model.getModel();
                                    if (uploadImage != null && !TextUtils.isEmpty(uploadImage.getFileUrl())) {
                                        imagePath = uploadImage.getFileUrl();
                                        complete();
                                    }
                                } else {
                                    closeDialog();
                                    Toast.makeText(SignActivity.this, "图片上传失败", Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onFail(String message, int code) {
                                Toast.makeText(SignActivity.this, "上传图片失败", Toast.LENGTH_SHORT).show();
                                closeDialog();
                            }
                        }, UploadImage.class);
                    }
                });

    }

    private void complete() {
        User user = DbUtil.getUser();
        if (user == null) {
            closeDialog();
            return;
        }
        List<String> image = new ArrayList<>();
        if (!TextUtils.isEmpty(imagePath))
            image.add(imagePath);
        List<String> ids = new ArrayList<>();
        if (selectList.size() > 0) {
            for (int i = 0; i < selectList.size(); i++) {
                ids.add(String.valueOf(selectList.get(i).getId()));
            }
        }
        LogUtil.e("====" + sceneId);
        NetUtils.getInstance().event(user.id, sceneId, myLatLng.longitude, myLatLng.latitude,
                mEtInput.getText().toString().trim(), 1, ids, image, manor.name, new NetCallBack() {
                    @Override
                    public void onSuccess(String message, int code, String response, ResultModel model) {
                        closeDialog();
                        if (code == Contants.SUCCESS_CODE) {
                            if (model == null) return;
                            SignCallBack signCallBack = model.getModel();
                            Intent intent = new Intent(SignActivity.this, DialogSignActivity.class);
                            intent.putExtra(Contants.TYPE, signCallBack);
                            intent.putExtra(Contants.OTHER_FIELD, manor);
                            startActivity(intent);
                            finish();
                            overridePendingTransition(R.anim.dialog_activity_enter, 0);
                            EventBus.getDefault().post(new MessageEvent(MessageEvent.MANOR));
                        } else {
                            if (!TextUtils.isEmpty(message)) {
                                Toast.makeText(SignActivity.this, message, Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFail(String message, int code) {
                        closeDialog();
                    }
                }, SignCallBack.class);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.alpha_out);
    }

    private void fistEnter() {

        final PopupWindowUtils popupWindowUtils = PopupWindowUtils.getInstance();
        popupWindowUtils.attachActivity(SignActivity.this, R.layout.sign_guide, mBottomSheetLayout)
                .wiewSize(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
                .location(Gravity.CENTER)
                .isDarkened(false)
                .Animation(PopupWindowUtils.ANIMATION_DIALOG)
                .setPopupWindowItemViewClickListener(new PopupWindowUtils.SetonPopWindowItemViewClickListenter() {
                    @Override
                    public void onPopWindowItemViewClickListener(int id) {
                        popupWindowUtils.dissMissPopWindow();
                        SPUtils.getInstance().put(Contants.SIGN_FIRST, false);
                    }
                }, R.id.v_pop)
                .show();
    }


}
